<template>
  <div class="grey_bg" ref="container">
    <navigate ref="navigate">
      {{ $route.query.name }}
      <template #right>
        <img
          class="dot_img"
          @click="menuVisible = !menuVisible"
          src="@/assets/images/common/dot.png"
          alt
        />
      </template>
    </navigate>

    <div class="message_all" ref="mess" @scroll="handleIsBottom()">
      <div class="message_item" v-for="(r, index) in list" :key="index">
        <!-- 类型【1普通消息，2自评，3测评任务】 -->
        <div class="message_normal"></div>
        <template v-if="r.type == 1">
          <div class="message_left" v-if="r.who == 2">
            <img
              :src="joinUrlImg(r.user_avatar)"
              alt=""
              class="messge_avatar"
            />
            <div class="message_speak">
              <div class="message_date">
                {{ formatDate(r.time * 1000, "yyyy/MM/dd") }}
              </div>
              <div class="speak_type">
                <div class="message_text" v-html="r.content"></div>
              </div>
            </div>
          </div>

          <div class="message_right" v-else>
            <div class="message_speak">
              <div class="message_date">
                {{ formatDate(r.time * 1000, "yyyy/MM/dd") }}
              </div>
              <div class="speak_type">
                <div class="message_text" v-html="r.content"></div>
              </div>
            </div>
            <img
              :src="joinUrlImg(r.user_avatar)"
              alt=""
              class="messge_avatar"
            />
          </div>
        </template>

        <template v-if="r.type == 3">
          <div class="message_left" v-if="r.who == 2">
            <img
              :src="joinUrlImg(r.user_avatar)"
              alt=""
              class="messge_avatar"
            />
            <div class="message_speak">
              <div class="message_date">
                {{ formatDate(r.time * 1000, "yyyy/MM/dd") }}
              </div>
              <div class="speak_type">
                <div class="message_scale">
                  <div class="scale_notice">
                    您收到了一份测评任务，请及时完成！
                  </div>
                  <div class="scale_task_box">
                    <div class="scale_task">
                      <img
                        class="scale_img"
                        :src="joinUrlImg(r.rating_scale_cover)"
                        alt=""
                      />
                      <div class="scale_name">{{ r.rating_scale_name }}</div>
                    </div>
                    <div class="scale_operate">
                      <div class="scale_summary">该量表还未完成。</div>
                      <button
                        class="btn task_btn flex_row flex_center_jc flex_align_center nowrap"
                        :class="{
                          is_disabled: r.is_over_scale == 1 || calcEnd,
                        }"
                        @click="startEvaluate(r)"
                      >
                        开始测评
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="message_right" v-else>
            <div class="message_speak">
              <div class="message_date">
                {{ formatDate(r.time * 1000, "yyyy/MM/dd") }}
              </div>
              <div class="speak_type">
                <div class="message_scale">
                  <div class="scale_notice">我已完成测评。</div>
                  <div class="scale_task_box">
                    <div class="scale_task">
                      <img
                        class="scale_img"
                        :src="joinUrlImg(r.rating_scale_cover)"
                        alt=""
                      />
                      <div class="scale_name">{{ r.task_name }}</div>
                    </div>
                    <div class="scale_operate">
                      <div class="scale_summary">我已完成该量表。</div>
                      <button
                        class="btn task_btn flex_row flex_center_jc flex_align_center nowrap"
                        :class="{ is_disabled: r.is_look == 0 }"
                        :disabled="r.is_look == 0"
                        @click="lookAnswer(r)"
                      >
                        答题情况
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <img
              :src="joinUrlImg(r.user_avatar)"
              alt=""
              class="messge_avatar"
            />
          </div>
        </template>

        <template v-if="r.type == 2">
          <div class="message_left" v-if="r.who == 2">
            <img
              :src="joinUrlImg(r.user_avatar)"
              alt=""
              class="messge_avatar"
            />
            <div class="message_speak">
              <div class="message_date">
                {{ formatDate(r.time * 1000, "yyyy/MM/dd") }}
              </div>
              <div class="speak_type">
                <div class="message_scale">
                  <div class="scale_notice">
                    您收到了一份近况自评表，请及时完成！
                  </div>
                  <div class="scale_task_box">
                    <div class="scale_task">
                      <img
                        class="scale_img"
                        src="@/assets/images/consult/self.png"
                        alt=""
                      />
                      <div class="scale_name">近况自评表</div>
                    </div>
                    <div class="scale_operate">
                      <div class="scale_summary">该自评表还未完成。</div>
                      <button
                        class="btn task_btn flex_row flex_center_jc flex_align_center nowrap"
                        :class="{
                          is_disabled:
                            r.is_over_self_assessment == 1 ||
                            calcBlackWhite ||
                            calcEnd,
                        }"
                        @click="startAssessment(r)"
                      >
                        开始测评
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="message_right" v-else>
            <div class="message_speak">
              <div class="message_date">
                {{ formatDate(r.create_time * 1000, "yyyy/MM/dd") }}
              </div>
              <div class="speak_type">
                <div class="message_scale">
                  <div class="scale_notice">
                    用户已完成近况自评表，请查看结果。
                  </div>
                  <div class="scale_task_box">
                    <div class="scale_task">
                      <img
                        class="scale_img"
                        src="@/assets/images/consult/self.png"
                        alt=""
                      />
                      <div class="scale_name">近况自评表</div>
                    </div>
                    <div class="scale_operate">
                      <div class="scale_summary">我已完成该自评表。</div>
                      <button
                        class="btn task_btn flex_row flex_center_jc flex_align_center nowrap"
                        @click="lookAssessment(r)"
                      >
                        答题情况
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <img
              :src="joinUrlImg(r.user_avatar)"
              alt=""
              class="messge_avatar"
            />
          </div>
        </template>
      </div>
      <div class="black_white_text" v-if="calcEnd || calcBlackWhite">
        {{
          calcEnd && calcBlackWhite
            ? "您被加入黑名单，本次咨询结束！"
            : calcEnd && !calcBlackWhite
            ? "本次咨询结束！"
            : ""
        }}
      </div>
    </div>

    <div class="send_message" ref="sendCtt">
      <div
        ref="content"
        spellcheck="false"
        :contenteditable="!(calcEnd || calcBlackWhite)"
        class="message_ctt"
        @input="inputChange"
      ></div>
      <button
        class="btn send_btn"
        :class="{ is_disabled: calcBlackWhite || calcEnd }"
        @click="sendMessage()"
      >
        发送
      </button>
    </div>

    <div class="small_menu" v-if="menuVisible">
      <div class="menu_item" @click="deleteRecord()">删除本条记录</div>
      <div class="menu_item" @click="consultantInfo()">咨询师详情</div>
    </div>
  </div>
</template>

<script>
import {
  queryConsultMeg,
  sendMeg,
  delOnConsultationRecord,
} from "@/api/consultation/record";

import { formatDate } from "@/utils/time";
import http from "@/server/http";
import { joinUrlImg } from "@/utils/setUrlImg";
export default {
  data() {
    return {
      containerHeight: 0,
      sendHeight: 0,
      navigateHeight: 0,
      isTextBottom: true,
      menuVisible: false,
      content: "",
      // 发送消息类型
      type: 1,
      // 消息列表
      list: [],
      timer: null,
      detailInfo: {},
    };
  },
  computed: {
    calcBlackWhite() {
      if (this.detailInfo) {
        return this.detailInfo.is_join_blacklist == 1;
      } else {
        return false;
      }
    },
    calcEnd() {
      if (this.detailInfo) {
        return this.detailInfo.is_end == 1;
      } else {
        return false;
      }
    },
  },
  created() {
    this.loop();
  },
  methods: {
    joinUrlImg,
    formatDate,
    // 轮询拿信息
    loop() {
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        this.getConsultMeg();
      }, 1000);
    },
    //查询咨询师详情
    consultantInfo() {
      this.$router.push(`/consultantInfo?id=${this.$route.query.consultId}`);
    },
    //删除记录
    deleteRecord() {
      this.menuVisible = !this.menuVisible;
      this.$popup({
        title: "提示",
        message: `<div>确定要删除本条记录吗？</div>`,
        confirmOperate: async () => {
          const params = {
            id: this.$route.query.id,
          };
          let res = await delOnConsultationRecord(params);
          if (res.code == 200) {
            this.$toast.success("删除成功");
            this.$router.back();
          }
        },
      });
    },
    //发送消息
    async getConsultMeg() {
      let res = await queryConsultMeg({ id: this.$route.query.id });
      if (res.code == 200) {
        this.list = res.data;
      }
    },
    //拉松
    async sendMessage() {
      const params = {
        online_id: this.$route.query.id,
        content: this.content,
      };
      let res = await sendMeg(params);
      if (res.code == 200) {
        this.getConsultMeg();
        this.content = "";
        this.$refs.content.innerHTML = "";
      }
    },
    // 结束

    // 前往测评页
    async startEvaluate(r) {
      if (r.is_over_scale == 1 || this.calcEnd || this.calcBlackWhite) {
        return;
      }
      if (r.is_read == 0) {
        await this.readTask(r.cp_id, 1, 0);
      }
      this.$router.push(
        `/normalAnswer?type=onlineConsult&sourceId=${r.id}&id=${r.rating_scale_id}`
      );
    },
    async startAssessment(r) {
      if (r.is_read == 0) {
        await this.readTask(r.task_id, 2, 0);
      }
      this.$router.push(`/selfAssessment/1/${r.task_id}`);
    },
    async lookAnswer(r) {
      if (r.result_read_auth == 0) return this.$toast.fail("没有查看权限");
      this.$router.push(`/evaluateExport?id=${r.id}&type=3`);
    },
    lookAssessment(r) {
      this.$router.push(`/selfAssessment/2/${r.task_id || 0}`);
    },

    // 获取会话列表
    async getChatList() {
      const { data } = await apiChatDetail({
        id: this.$route.params.id,
        page: 1,
        page_size: 999999,
      });
      if (data.code == 200) {
        this.list = data.data.data;
      }
    },

    async readTask(id, type, uid) {
      await http({
        url: "/psychological/scheduling/set_dot",
        method: "POST",
        data: { id, type, uid },
      });
    },
    async getDetailsInfo() {
      let { data } = await http({
        url: "/psychological/scheduling/log_describe",
        method: "POST",
        data: {
          id: this.$route.params.id,
        },
      });
      if (data.code == 200) {
        this.detailInfo = data.data;
      }
    },
    inputChange(v) {
      let content = v.target.innerHTML;
      this.content = content;
      this.getHeight();
    },
    getHeight() {
      this.sendHeight = this.$refs.sendCtt.clientHeight;
      this.$refs.mess.style.height =
        this.containerHeight - this.sendHeight - this.navigateHeight + "px";
      if (this.isTextBottom) {
        this.scrollCtt();
      }
    },
    handleIsBottom() {
      let maxHeight = this.$refs.mess.offsetHeight;
      let allHeight = this.$refs.mess.scrollHeight;
      let top = this.$refs.mess.scrollTop;
      if (top < Math.round(allHeight - maxHeight)) {
        this.isTextBottom = false;
      } else {
        this.isTextBottom = true;
      }
    },
    scrollCtt() {
      let maxHeight = this.$refs.mess.offsetHeight;
      let allHeight = this.$refs.mess.scrollHeight;
      if (allHeight > maxHeight) {
        this.$refs.mess.scrollTop = Math.round(allHeight - maxHeight);
      }
    },
  },

  mounted() {
    this.containerHeight = this.$refs.container.clientHeight;
    this.navigateHeight = document.querySelector(".header").clientHeight;
    this.getHeight();
    this.scrollCtt();
  },
  updated() {
    if (this.isTextBottom) {
      this.scrollCtt();
    }
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<style scoped>
.grey_bg {
  background: #f4f6fa;
}
.text_ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.text_justify {
  text-align: justify;
  word-break: keep-all;
}

.dot_img {
  width: 20.83px;
  height: 20.83px;
}

.send_message {
  width: 100%;
  height: auto;
  background: #f7f7f7;
  display: flex;
  gap: 6.94px;
  align-items: flex-end;
  padding: 8.68px 10.42px;
  box-sizing: border-box;
  position: sticky;
  bottom: 0;
  left: 0;
}
.message_ctt {
  width: 277.78px;
  height: auto;
  min-height: 38.19px;
  max-height: calc(100px - 8.68px * 2);
  background: #ffffff;
  border: 0.35px solid #dddddd;
  border-radius: 6.94px;
  overflow-y: auto;
  outline: none;
  font-size: 13.89px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  padding: 9.5475px;
  box-sizing: border-box;
  color: #888888;
}
.send_btn {
  width: 69.44px;
  height: 38.19px;
  font-size: 14.58px;
}
.btn.is_disabled {
  opacity: 0.3;
}

.message_all {
  overflow-y: auto;
  padding: 34.72px 10.42px;
  box-sizing: border-box;
}
.message_item:not(:last-child) {
  margin-bottom: 20.83px;
}

.task_btn {
  width: 69.44px;
  height: 31.25px;
  border-radius: 3.47px;
  font-size: 13.19px;
}
.message_left,
.message_right {
  display: flex;
  gap: 11.11px;
}
.message_right {
  justify-content: flex-end;
}
.messge_avatar {
  width: 38.19px;
  height: 38.19px;
}
.message_date {
  height: 12.85px;
  line-height: 12.85px;
  font-size: 11.11px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  color: #aaaaaa;
  margin-bottom: 5.55px;
}
.message_text {
  max-width: 262.15px;
  min-height: 42.36px;
  line-height: 20.83px;
  padding: 10.065px 13.89px;
  box-sizing: border-box;
  font-size: 14.58px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: bold;
  text-align: left;
}

.speak_type {
  width: fit-content;
  position: relative;
  border-radius: 6.94px;
}
.speak_type::before {
  position: absolute;
  top: 6.95px;
  content: "";
  width: 5.2px;
  height: 0;
  border: 6.95px solid transparent;
}
.message_scale {
  width: 262.15px;
  height: max-content;
  padding: 10.42px 10.42px 13.89px 10.42px;
  box-sizing: border-box;
}
.scale_notice {
  width: 224.31px;
  font-size: 14.58px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: bold;
  line-height: 20.83px;
  /* margin-bottom: 14.93px; */
  margin-bottom: 12px;
}
.scale_task_box {
  width: 236.11px;
  height: 104.17px;
  border-radius: 6.94px;
  padding: 10.42px;
  box-sizing: border-box;
}
.scale_task {
  display: flex;
  align-items: center;
  gap: 10.42px;
  margin-bottom: 10px;
}
.scale_img {
  width: 41.67px;
  height: 41.67px;
  border-radius: 6.94px;
}
.scale_name {
  width: 132.64px;
  height: 39.58px;
  font-size: 14.58px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  text-align: left;
  color: #333333;
  line-height: 1.5;
  word-break: break-all;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.scale_operate {
  display: flex;
  justify-content: space-between;
}
.scale_summary {
  height: 31.25px;
  font-size: 13.19px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  text-align: left;
  color: #888888;
  line-height: 31.25px;
}

.message_left .message_date {
  text-align: left;
}
.message_right .message_date {
  text-align: right;
}
.message_left .speak_type {
  background: rgba(255, 255, 255, 1);
  color: rgba(51, 51, 51, 1);
}
.message_right .speak_type {
  background: rgba(0, 174, 255, 1);
  color: #ffffff;
}
.message_left .speak_type::before {
  border-right-color: rgba(255, 255, 255, 1);
  left: -17px;
}
.message_right .speak_type::before {
  border-left-color: rgba(0, 174, 255, 1);
  right: -17px;
}
.message_left .scale_notice {
  color: #333333;
}
.message_right .scale_notice {
  color: rgba(255, 255, 255, 1);
}
.message_left .scale_task_box {
  background: rgba(240, 240, 240, 0.3);
  border: 0.35px solid rgba(102, 102, 102, 0.3);
}
.message_right .scale_task_box {
  background: rgba(255, 255, 255, 1);
  border: 0.35px solid rgba(255, 255, 255, 1);
}

.black_white_text {
  width: 100%;
  height: 100px;
  line-height: 100px;
  font-size: 13.19px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  text-align: center;
  color: #888888;
  margin-top: 41.33px;
}

.small_menu {
  width: 131.94px;
  height: fit-content;
  background: rgba(51, 51, 51, 0.9);
  border-radius: 6.94px;
  padding: 0 6.94px;
  box-sizing: border-box;
  position: absolute;
  top: 70.42px;
  right: 10.42px;
}
.menu_item {
  width: 100%;
  height: 55.56px;
  line-height: 55.56px;
  font-size: 14.58px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  text-align: center;
  color: #ffffff;
  position: relative;
}
.menu_item:not(:last-child)::before {
  display: block;
  width: 100%;
  height: 0.35px;
  background: rgba(255, 255, 255, 0.5);
  position: absolute;
  bottom: 0;
  left: 0;
  content: "";
}
</style>
